package net.chengp.ms.auth.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import net.chengp.ms.auth.service.UserDetails;

/**
 * JWT内容增强（封装需要得信息进jwt）
 * 
 * @author chengp
 *
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		if (authentication.getPrincipal() instanceof UserDetails) {
			UserDetails securityUser = (UserDetails) authentication.getPrincipal();
			Map<String, Object> info = new HashMap<>();
			// 把用户名称设置到JWT中
			info.put("username", securityUser.getUsername());
			((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
		}
		return accessToken;
	}

}
